<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "9c84d93b"
    });
  daovoice('update');
  </script>












<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.1.0" color="#222">







<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>


<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="集合类1.能否用任何类作为 Map 的 Key？  如果类重写了 equals()方法，也应该重写 hashCode()方法 类的所有实例需要遵循与 equals() 和 hashCode() 相关的规则 如果一个类灭有使用 equals()，不应该在 hashCode()中使用它 用户自定义 Key 类最佳实践是使之为不可变，这样 hashCode()值可以被缓存起来，拥有更好的性能  分析：如">
<meta name="keywords" content="java,面试">
<meta property="og:type" content="article">
<meta property="og:title" content="必知必会Java面试题">
<meta property="og:url" content="http://zhangsnke.gitee.io/2019/01/11/集合类/index.html">
<meta property="og:site_name" content="Zhangsnke&#39;s Blog">
<meta property="og:description" content="集合类1.能否用任何类作为 Map 的 Key？  如果类重写了 equals()方法，也应该重写 hashCode()方法 类的所有实例需要遵循与 equals() 和 hashCode() 相关的规则 如果一个类灭有使用 equals()，不应该在 hashCode()中使用它 用户自定义 Key 类最佳实践是使之为不可变，这样 hashCode()值可以被缓存起来，拥有更好的性能  分析：如">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz2o0igth7j30fu09bmx5.jpg">
<meta property="og:updated_time" content="2019-01-11T08:40:15.252Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="必知必会Java面试题">
<meta name="twitter:description" content="集合类1.能否用任何类作为 Map 的 Key？  如果类重写了 equals()方法，也应该重写 hashCode()方法 类的所有实例需要遵循与 equals() 和 hashCode() 相关的规则 如果一个类灭有使用 equals()，不应该在 hashCode()中使用它 用户自定义 Key 类最佳实践是使之为不可变，这样 hashCode()值可以被缓存起来，拥有更好的性能  分析：如">
<meta name="twitter:image" content="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz2o0igth7j30fu09bmx5.jpg">






  <link rel="canonical" href="http://zhangsnke.gitee.io/2019/01/11/集合类/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>必知必会Java面试题 | Zhangsnke's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/zxk318www"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhangsnke's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
          
  
  <li class="menu-item menu-item-home menu-item-active">
    <a href="/blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-about">
    <a href="/blog/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-tags">
    <a href="/blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-categories">
    <a href="/blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-archives">
    <a href="/blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
</li>

      

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsnke.gitee.io/blog/2019/01/11/集合类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zhangsnke">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz2r82s43bj30u20u0ad9.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhangsnke's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">必知必会Java面试题</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-11T16:40:14+08:00">2019-01-11</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/java面试题/" itemprop="url" rel="index"><span itemprop="name">java面试题</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2019/01/11/集合类/#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/blog/2019/01/11/集合类/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="集合类"><a href="#集合类" class="headerlink" title="集合类"></a>集合类</h3><p><strong>1.能否用任何类作为 Map 的 Key？</strong></p>
<ul>
<li>如果类重写了 equals()方法，也应该重写 hashCode()方法</li>
<li>类的所有实例需要遵循与 equals() 和 hashCode() 相关的规则</li>
<li>如果一个类灭有使用 equals()，不应该在 hashCode()中使用它</li>
<li>用户自定义 Key 类最佳实践是使之为不可变，这样 hashCode()值可以被缓存起来，拥有更好的性能</li>
</ul>
<p><em>分析：如果有一个类 MyKey ，在 HashMap中使用它：</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">HashMap&lt;MyKey,String&gt; myHashMap = <span class="keyword">new</span> HashMap&lt;MyKey,String&gt;();</span><br><span class="line"><span class="comment">//传递给 MyKey 的 name 参数被用于 equals()和hashCode()中</span></span><br><span class="line">MyKey mykey = <span class="keyword">new</span> MyKey(<span class="string">"zxk"</span>); <span class="comment">//假设当前 hashCode = 111</span></span><br><span class="line">myHashMap.put(mykey,<span class="string">"value"</span>);</span><br><span class="line"><span class="comment">//以下代码会改变 key 的 hashCode() 和 equals()值</span></span><br><span class="line">mykey.setName(<span class="string">"Change"</span>); <span class="comment">//新的 hashCode = 222</span></span><br><span class="line"><span class="comment">//西面会返回null，因为 HashMap 会尝试查找存储同样索引的 key,而 key已经被改变了，匹配失败</span></span><br><span class="line">System.out.print(myHashMap.get(<span class="keyword">new</span> MyKey(<span class="string">"zxk"</span>)));</span><br></pre></td></tr></table></figure></p>
<p><em>这就是为什么String经常会被作为 HashMap的 Key，因为 String 的设计不可变。</em></p>
<p><strong>2.插入数据时，ArrayList、LinkedList、Vector谁的速度比较快？</strong></p>
<ul>
<li>ArrayList、Vector 底层的实现都是数组，数组元素大于实际存储的数据以便增加和插入元素，它们都允许直接按序号索引元素，但是插入元素要涉及到元素移动等内存操作，所以索引数据（查找数据）比插入数据更快</li>
<li>Vector 中方法由于加了 synchronized 修饰，因此 Vector 是线程安全容器，但性能上比 ArrayList 差些</li>
<li>LinkedList 底层的实现是双向链表，按序号索引数据需要进行向前或向后的遍历，但是插入数据时只需要记录当前项的前后项即可，所以 LinkedList 插入数据速度快，是三者中最快的，但是查找数据比较慢</li>
</ul>
<p><strong>3.多线程场景下如何使用 ArrayList？</strong><br><em>ArrayList 是线程不安全的，如果遇到多线程情况下，可以通过 Collections 的 synchronizedList 方法将其装换成线程安全的容器后在使用。</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; synchronizedList = Collections.synchronizedList(list);</span><br><span class="line">synchronizedList.add(<span class="string">"aaa"</span>);</span><br><span class="line">synchronizedList.add(<span class="string">"bbb"</span>);</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i&lt;synchronizedList.size();i++)&#123;</span><br><span class="line">	System.out.println(synchronizedList.get(i));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>4.ArrayList优缺点</strong></p>
<p><em>优点：</em></p>
<ol>
<li>ArrayList 底层是以数组实现，是一种随机访问模式，ArrayList 实现了 RandomAccess 接口，因此查找的时候非常快速。</li>
<li>ArrayList 在顺序添加一个元素的时候非常方便。</li>
</ol>
<p><em>缺点：</em></p>
<ol>
<li>删除元素的时候，需要做一次元素复制的操作，如果复制到元素很多，那么就会比较耗费性能。</li>
<li>插入元素的时候，也需要做一次元素复制操作，缺点同上。</li>
</ol>
<p>ArrayList 比较是否 顺序添加、随机访问的场景。</p>
<p><strong>5.为什么 ArrayList 的 elementData 加上 transient 修饰</strong></p>
<p>ArrayList中数组定义：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">transient</span> Object[] elementData;</span><br></pre></td></tr></table></figure></p>
<p>ArrayList 的定义：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArrayList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbsratctList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;,<span class="title">RandomAccess</span>,<span class="title">Cloneable</span>,<span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span></span><br></pre></td></tr></table></figure></p>
<p>可以看到 ArrayList 实现了 Serializable 接口，这意味着 ArrayList 支持序列化。transient 的作用是说为了 elementData 数组被序列化，重写了 writeObject 实现：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">writeObject</span><span class="params">(java.io.ObjectOutputStream s)</span> <span class="keyword">throws</span> java.io.IOException</span>&#123;</span><br><span class="line">	<span class="comment">//Write out element count, and any hidden stuff</span></span><br><span class="line">	<span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">	s.defaultWriteObject();</span><br><span class="line">	<span class="comment">//write out array length</span></span><br><span class="line">	s.writeInt(elementData.length);</span><br><span class="line">	<span class="comment">//write out all elements in the proper order</span></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;size;i++)</span><br><span class="line">		s.writeObject(elementData[i]);</span><br><span class="line">	<span class="keyword">if</span>(modCount != expectedModCount)&#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>每次序列化时，先调用 defaultWriteObject()方法序列化 ArrayList 中的非 transient 元素，然后遍历 elementData ，只序列化已存入的元素，这样即加快了序列化的速度，又减小序列化之后的文件大小。</p>
<p><strong>6.遍历一个List有哪些方式，每种方式实现原理是什么，Java中遍历List最佳实践是什么？</strong></p>
<ol>
<li><font color="red">for 循环遍历</font>：基于计数器，在集合外部维护一个计数器，然后依次读取每一个位置的元素，当读取到最后一个元素后停止。</li>
<li><font color="red">迭代器遍历</font>：Iterator 是面向对象的一个设计模式，目的是屏蔽不同数据集合的特点，统一遍历集合的接口。Java 在 Collections 中支持了 Iterator 模式。</li>
<li><font color="red">foreach 循环遍历</font>：foreach 内部采用了 Iterator 的实现方式，使用时不需要显式声明 Iterator 或计数器。优点是代码简洁，不易出错；缺点是只能简单的遍历，不能在遍历过程中操作元素。例如删除、替换。</li>
</ol>
<p><font color="bliue">最佳实践：</font> Java Collections 框架中提供了一个 RandomAccess 接口，用来标记 List 实现是否支持 Random Access。</p>
<ul>
<li>如果一个数据集合实现了该接口，就意味着它支持 Random Access，按照位置读取元素的平均时间复杂度 O(1)，如ArrayList。</li>
<li>如果没有实现该接口，表示不支持 Random Access ，如 LinkedList。<br><em><font color="blue">推荐做法：支持 Random Access 的列表可以用 for 循环遍历，否则建议用 Iterator 或 foreach 遍历。</font></em></li>
</ul>
<p><strong>7.如何一边遍历一边移除 Collection 中的元素？</strong></p>
<p>采用 Iterator.remove()方法。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Iterator&lt;Integer&gt; it  = list.iterator();</span><br><span class="line"><span class="keyword">while</span>(it.hasNext())&#123;</span><br><span class="line">	<span class="comment">// do something</span></span><br><span class="line">	it.remove();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><font color="bluie">特别指出一种错误的方式：<font><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这种错误会报 ConcurrentModificationException异常</span></span><br><span class="line"><span class="keyword">for</span>(Integer i : list)&#123;</span><br><span class="line">	list.remove(i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></font></font></p>
<p><em>因为在使用 foreach(for(Integer i : list)) 语句时，会自动生成一个 Iterator 来遍历该 list ，但同时该 list 正在被 Iterator.remove() 修改。 Java 一般不允许一个线程 在遍历 Collection 时另一个线程修改它。</em></p>
<hr>
<h3 id="封装类、String、String-Pool、StringBuilder"><a href="#封装类、String、String-Pool、StringBuilder" class="headerlink" title="封装类、String、String Pool、StringBuilder"></a>封装类、String、String Pool、StringBuilder</h3><p><strong>1.写出下面代码的运行结果</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> src = <span class="number">65536</span>;</span><br><span class="line">Integer dst = <span class="keyword">new</span> Integer(<span class="number">65536</span>);</span><br><span class="line">System.out.println( src == dst);</span><br><span class="line">System.out.println( dst.equals(src) );</span><br></pre></td></tr></table></figure></p>
<p><em>都是 true 。Integer 的 equals 实现。65536 装箱为 Integer 对象后，dst.equals() 方法比较的是 obj.intValue()。 </em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object obj)</span></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (obj <span class="keyword">instanceof</span> Integer)&#123;</span><br><span class="line">		<span class="keyword">return</span> value == ((Integer) obj).intValue();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>2.写出下面代码的运行结果</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Example</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sayHello</span><span class="params">()</span></span>&#123;</span><br><span class="line">		System.out.println(<span class="string">"hello!"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">		((Example)<span class="keyword">null</span>).sayHello();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><em>最终输出“hello!”。null 作为非基本类型，可以做类型转换，转换后调用静态方法输出字符串。基本类型，比如 int ，类型转换时会报空指针异常，比如 int a= (Integer)null；原因是转换过程中会调用 intValue()，因此会报出异常。</em></p>
<p><strong>3.String 类能被继承么</strong><br><em>不能。因为 String 类定义为 final class ，被 final 修饰的类不能被继承。</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">String</span></span></span><br></pre></td></tr></table></figure></p>
<ul>
<li>String pool：这是方法（method）区域里一个特殊的存储区域，创建一个 String 时，如果已经在 String pool 中存在，那么会返回已存在的 String 引用。</li>
<li>允许 String 缓存 hashCode：String 定义中，有 hash 成员变量 private int hash （默认为0）对 hashCode 进行缓存。</li>
<li>安全性：保证不会被恶意篡改。</li>
</ul>
<p><strong>4.String s3 = new String(“a”)会创建几个 String 对象</strong><br><em>1个或 2 个。</em><br><em>String pool 机制。如果 Spring pool在执行语句之前 没有 “a” 对象，那么会创建 2 个String,如果已经存在，“a”会从 String pool 中直接返回对象</em></p>
<p><strong>5.String、StringBuffer、StringBuilder区别</strong></p>
<ol>
<li>String 是不可变得，StringBuffer、StringBuilder 是可变的</li>
<li>String、StringBuffer 是线程安全的，StringBuilder 不是线程安全的</li>
<li>StringBuilder 比 StringBuffer 有速度优势。但是应用在要求线程安全情况下，需要使用 StringBuffer</li>
</ol>
<p><strong>6.为什么针对安全保密高的信息，char[]比String更好？</strong><br><em>String 是不可变的，一旦创建，就不能再改变，直到垃圾收集器将它回收。而字符数组中的元素是可以更改的，这就意味着可以在使用完后将其更改，而且不会保留原始数据，</em></p>
<h3 id="3-常见问题"><a href="#3-常见问题" class="headerlink" title="3.常见问题"></a>3.常见问题</h3><p><strong>1.Object类包含哪些方法？</strong><br><em>在 java.lang 包中，Object 类位于类层次结构的顶端。每个类都是 Object 类直接或间接的子类。以下是从 Object 类中继承的方法：</em></p>
<ul>
<li>protected Object clone() throws CloneNotSupportedException 创建并返回此对象的副本</li>
<li>public boolean equals(Object o) 判断另一个对象是否与此对象相等</li>
<li>protected void finalize() throws Throwable 当垃圾回收机制确定该对象不再被调用时，垃圾回收器会调用此方法</li>
<li>public final Class getClass() 返回此对象的运行时类</li>
<li>public int hashCode() 返回此对象的散列码值</li>
<li>public String toString() 返回此对象的字符串表示形式</li>
</ul>
<p><strong>2.final、finally、finalize 三者不同</strong></p>
<ul>
<li>final 关键字用于多个语境下定义只能分配一次的实体</li>
<li>finally 代码块用于执行重要代码（如关闭连接、流等）的代码块，无论是否异常处理，finally 代码块总会被执行，finally 代码块紧随着 try 代码块或者 catch 代码块</li>
<li>finalize 这是在删除或销毁对象之前垃圾回收器总会调用的方法，该方法是的垃圾回收机制能够执行清理活动</li>
</ul>
<p><strong>3.菱形继承问题(钻石继承问题)</strong><br><img src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz2o0igth7j30fu09bmx5.jpg" alt="图1"><br>jdk1.8之前不允许出现多继承（extends），但是1.8之后，由于接口添加定义方法（default method）可以实现接口多继承。</p>
<p><strong>4.如何使一个类不可改变</strong></p>
<ol>
<li>将类声明为 final，使其无法被继承。</li>
<li>所有域都用 private 修饰，不允许直接访问</li>
<li>不提供变量的 setter 方法</li>
<li>所有可变域都用 final 修饰，使它的值只能分配一次</li>
<li>通过构造函数执行深克隆初始化所有域</li>
<li>对 getter 方法获取的对象执行克隆返回副本，而不是返回实际的对象引用</li>
</ol>
<p><strong>5.单例模式</strong><br><em>单例模式指的一个类仅允许创建其自身的一个实例，并提供对该实例的访问权限。它包含静态变量，可以容纳其自身的唯一和私有实例。一般应用场景：用户希望类的实例被约束为一个对象。</em></p>
<ol>
<li><p>饿汉模式（静态常量）[可用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//优点：写法比较简单，就是在类加载的时候就完成实例化，避免了线程同步问题</span></span><br><span class="line"><span class="comment">//缺点：类装载的时候就完成了实例化，没有达到懒加载（Lazy Loading）效果，如果从始至今都没用到郭这个实例，就会出现内存浪费</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Singleton INSTANCE = <span class="keyword">new</span> Singleton();</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> INSTANCE;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>饿汉模式（静态代码块）[可用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//该方式和上述方式类似，只不过将类的实例化放到了静态代码块中，也是在类加载的时候，执行静态代码块，初始化实例，优缺点和上述一样。</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Singleton instance;</span><br><span class="line">	<span class="keyword">static</span> &#123;</span><br><span class="line">		instance = <span class="keyword">new</span> Singleton();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> instance;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>懒汉模式（线程不安全）[不可用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这种写法起到了懒加载（Lazy Loading）效果，但是只能在单线程下使用。如果多线程下，一个线程进入了 if(singleton == null)判断语句块，还未来得及往下执行，另一个线程也进入了这个判断语句，便会产生多个实例，所以在多线程下不可以用</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Singleton singleton;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (singleton == <span class="keyword">null</span>)&#123;</span><br><span class="line">			singleton = <span class="keyword">new</span> Singleton();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> singleton;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>懒汉式（线程安全，同步方法）[不推荐使用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//加了同步锁（synchronized）,解决第三种方式的线程不安全。</span></span><br><span class="line"><span class="comment">//缺点：效率太低，每个线程在获得类实例的时候，需要执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了，方法进行同步效率太低。</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Singleton singleton;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (singleton == <span class="keyword">null</span>)&#123;</span><br><span class="line">			singleton = <span class="keyword">new</span> Singleton();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> singleton;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>懒汉式（线程安全，同步代码块）[不可用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//由于第四种实现方式同步效率太低，所以摒弃了同步方法，改为同步产生实例化的代码块。但是这种同步不能起到线程同步的作用。跟第三种实现方式情形一致。如果一个线程进入了 if(singleton == null)判断语句块，另一个语句也进入了，也会产生多个实例</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> Singleton singleton;</span><br><span class="line">	<span class="keyword">private</span> Singleton&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (singleton == <span class="keyword">null</span>)&#123;</span><br><span class="line">			<span class="keyword">synchronized</span> (Singleton.class)&#123;</span><br><span class="line">				singleton = <span class="keyword">new</span> Singleton();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> singleton;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>双重检查[推荐用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Double-Check，进行两次 if(singleton == null)检查，这样可以保证线程安全，实例化代码只进行一次，后面咋次访问时，依旧判断 if (singleton == null)，直接return 实例化对象</span></span><br><span class="line"><span class="comment">//优点：线程安全，延迟加载，效率更高。</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Singleton singleton;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (singleton == <span class="keyword">null</span>)&#123;</span><br><span class="line">			<span class="keyword">synchronized</span>(Singleton.class)&#123;</span><br><span class="line">				<span class="keyword">if</span>(singleton == <span class="keyword">null</span>)&#123;</span><br><span class="line">					singleton = <span class="keyword">new</span> Singleton();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> singleton;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>静态内部类[推荐用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这种方式跟饿汉方式采用的机制类似，又有区别。两者都是采用类加载的机制来保证实例化时只有一个线程，不同的地方是饿汉方式只要 Singleton类被加载就会实例化，没有懒加载（Lazy Loading）的作用，而静态内部类方式在Singleton类被加载时并不会直接实例化，而是调用getInstance方法，才会装载SingletonInstance类，从而完成Singleton实例化</span></span><br><span class="line"><span class="comment">//类的静态属性只有第一次加载类的时候才会初始化，这里，JVM保证了线程安全，在类进行初始胡时，别的线程是无法进入的</span></span><br><span class="line"><span class="comment">//优点：避免了线程不安全，延迟加载，效率高。</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SingletonInstance</span></span>&#123;</span><br><span class="line">		<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Singleton INSTANCE = <span class="keyword">new</span> Singleton();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> SingletonInstance.INSTANCE;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>枚举[推荐用]</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//借助JDK1.5添加的枚举来实现单例，不仅避免了多线程同步问题，而且还能防止反序列化重新创建的对象</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> Singleton&#123;</span><br><span class="line">	INSTANCE;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> Singleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> INSTANCE;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><a href="https://www.cnblogs.com/chiclee/p/9097772.html" target="_blank" rel="noopener">点击=&gt;查看枚举实现单例</a></p>
<p><strong>6.什么是依赖注入？</strong><br><em>Dependency Injection <font color="red">依赖注入</font>和 Inversion of Controller <font color="red">控制反转</font>是同一个概念的不同角度描述。</em></p>
<p><font color="bloi">具体含义：</font><br><em>当某个角色（可能是一个 Java 实例，调用者）需要另一个角色（另一个 Java 实例，被调用者）的协助时，传统的程序设计中，通常是由调用者来创建被调用者的实例。在Spring里，创建被调用者的工作不再由调用者来完成，因此成为控制反转，创建被调用者 实例工作 通常由Spring容器来完成，然后注入调用者，因此成为依赖注入。</em><br><a href="https://blog.csdn.net/coding_1994/article/details/80634810" target="_blank" rel="noopener">依赖注入</a><br><a href="https://blog.csdn.net/qq_42709262/article/details/81951402" target="_blank" rel="noopener">IOC和DI</a></p>

      
    </div>

    

    
    
    

<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fq7f9mgftqj30yf11x793.jpg" alt="Zhangsnke 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fq7f9yogljj30ox0qi76z.jpg" alt="Zhangsnke 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/blog/tags/面试/" rel="tag"><i class="fa fa-tag"></i> 面试</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/01/10/1. 简介：/" rel="next" title="Java集合">
                <i class="fa fa-chevron-left"></i> Java集合
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/01/15/Java多线程/" rel="prev" title="Java多线程">
                Java多线程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="uyan_frame"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz2r82s43bj30u20u0ad9.jpg"
                alt="Zhangsnke" />
            
              <p class="site-author-name" itemprop="name">Zhangsnke</p>
              <p class="site-description motion-element" itemprop="description">java jsp</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">11</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">8</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zxk318www" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1137824821@qq.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/u/3487862312" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#集合类"><span class="nav-number">1.</span> <span class="nav-text">集合类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#封装类、String、String-Pool、StringBuilder"><span class="nav-number">2.</span> <span class="nav-text">封装类、String、String Pool、StringBuilder</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-常见问题"><span class="nav-number">3.</span> <span class="nav-text">3.常见问题</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhangsnke</span>

  

  
</div>




<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>
  <!-- <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Muse</a> v6.1.0</div>
-->





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共28.7k字</span>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2161053"></script>
      <!-- UY END -->
    
  





  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'V4OQTBV0QUJvAOnALRUDikMp-gzGzoHsz',
        appKey: 'Ygfy3JqhxL8KArimEFAGB3QQ',
        placeholder: 'ヾﾉ≧∀≦)o来啊，快活啊!',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
</body>
</html>

